Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
Is there a way to efficiently "pivot" a multidimensional array?

I have an array of arrays formatted the following way:

[['BTC', '2022-04-27', '39151.53'],
 ['BTC', '2022-04-26', '37730.20'],
 ['BTC', '2022-04-25', '39151.53'],
 ['ETH', '2022-04-27', '39151.53'],
 ['ETH', '2022-04-26', '37730.20'],
 ['ETH', '2022-04-25', '39151.53']]

What I would like to end up with is:

[['Date', 'BTC, 'ETH'],
 ['2022-04-27', '39151.53', '39151.53'],
 ['2022-04-26', '37730.20', '39151.53'],
 ['2022-04-25', '39151.53', '39151.53']]

Is there any non-complicated way to solve it?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You could take an object with the types fo the columns and the indices of the target. Then find the row and assign the type to the wanted cell.

const
    data = [['BTC', '2022-04-27', '39151.53'], ['BTC', '2022-04-26', '37730.20'], ['BTC', '2022-04-25', '39151.53'], ['ETH', '2022-04-27', '39151.53'], ['ETH', '2022-04-26', '37730.20'], ['ETH', '2022-04-25', '39151.53']],
    types = { Date: 0, BTC: 1, ETH: 2 },
    result = data.reduce((r, [type, date, value]) => {
        let row = r.find(a => a[types.Date] === date);
        if (!row) r.push(row = [date, ...Array(Object.keys(types).length - 1).fill('0')]);
        row[types[type]] = value;
        return r;
    }, [Object.keys(types)]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

It looks like the OP needs the inner arrays indexed by the date field. This can be done with reduce. Once there's an index, walk through the keys (dates) and collect the values associated with each date.

const array = [['BTC', '2022-04-27', '39151.53'],
 ['BTC', '2022-04-26', '37730.20'],
 ['BTC', '2022-04-25', '39151.53'],
 ['ETH', '2022-04-27', '39151.53'],
 ['ETH', '2022-04-26', '37730.20'],
 ['ETH', '2022-04-25', '39151.53']];

const dateIndex = array.reduce((acc, a) => {
  let date = a[1];
  if (!acc[date]) acc[date] = [];
  acc[date].push(a);
  return acc;
}, {});


let result = [['Date', 'BTC', 'ETH']];
Object.keys(dateIndex).map(date => {
  let values = dateIndex[date].map(arr => arr[2]);
  result.push([date, ...values]);
});

console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

Here another solution using reduce().

This first creates a JavaScript object which would allow for quick lookups of a specific value for a given currency and date within a program and then transforms that object to create the result requested by OP. It will also throw an error for incorrect input data when e.g. there would be two values for a given currency and date.

const input = [
  ["BTC", "2022-04-27", "39151.53"],
  ["BTC", "2022-04-26", "37730.20"],
  ["BTC", "2022-04-25", "39151.53"],
  ["ETH", "2022-04-27", "39151.53"],
  ["ETH", "2022-04-26", "37730.20"],
  ["ETH", "2022-04-25", "39151.53"],
];

function pivot(input){
  return input.reduce((perDay, [currency, date, value]) => {
    if(perDay[date]) {
      // we already have a value for this day
      if(perDay[date][currency]){
        // we already have a value for this currency and day => error
        throw new Error(`Two values for for the same day. Currency: ${currency}, Day: ${date}`);
      }
      // add value for another currency for that day
      else perDay[date][currency] = value;
    } else perDay[date] = { [currency]: value };
    return perDay; 
  }, {})
}

// result as a JS object which will allow quick lookups
const pivotted = pivot(input);
console.log("Result as JavaScript object")
console.log(pivotted);

// result transformed to your expected result
const result = Object.entries(pivotted).map(([date, values]) => [date, ...Object.values(values)]);
result.unshift(['Date', 'BTC', 'ETH']);
console.log("Result as JavaScript nested array")
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda